package gas.backend;

import gas.backend.tac.ICTac;

import java.util.ArrayList;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;

enum ICTYPE {
	NA, ARRAY, FILE
}

public class IntermediateCodeReader {
	public int count;
	private ICTYPE icType;
	private ArrayList<String> icArray;
	private FileReader icFileReader;
	private BufferedReader icBufferedReader;

	protected IntermediateCodeReader() {
		reset();
	}
	
	protected IntermediateCodeReader(Object ic) {
		setIntermediateCode(ic);
	}

	protected void reset() {
		count = 0;
		icType = ICTYPE.NA;
		icArray = null;
		icFileReader = null;
		icBufferedReader = null;
	}
	
	protected void setIntermediateCode(Object ic) {
		if (ic instanceof ArrayList<?>) {
			count = 0;
			icType = ICTYPE.ARRAY;
			// TODO: How to?
			icArray = (ArrayList<String>)ic;
		} 
		else if (ic instanceof String) {
			count = 0;
			icType = ICTYPE.FILE;
			String filepath = new String((String)ic);
			try {
				icFileReader = new FileReader(filepath);
				icBufferedReader = new BufferedReader(icFileReader);
				icArray = new ArrayList<String>();
			}
			catch (FileNotFoundException fnfe) {
				reset();
				System.out.println("ERROR back-end 002");
			}
		}
		else {
			System.out.println("ERROR back-end 001");
		}
	}
	
	private String nextLine() {
		String ret = null;
		if(icType == ICTYPE.ARRAY) {
			if(count < icArray.size()) {
				ret = new String(icArray.get(count));
				count++;
			}
			else {
				return null;
			}
		}
		else if (icType == ICTYPE.FILE) {
			System.out.println(count);
			if(count < icArray.size()) {
				ret = new String(icArray.get(count));
				count++;
			}
			else {
				try {
					ret = new String(icBufferedReader.readLine());
					icArray.add(ret);
					count++;
				}
				catch (IOException ioe) {
					System.out.println("ERROR back-end 004");
					return null;
				}
			}
		}
		else {
			System.out.println("ERROR back-end 003");
			return null;
		}
		
		return ret;
	}
	
	private String getLineByIndex(int index) {
		if(icArray != null) {
			if(index < icArray.size()) {
				return new String(icArray.get(index));
			}
		}
		return null;
	}

	protected ICTac nextTac() {
		String line = nextLine();
		if (line != null) {
			return new ICTac(line);
		} else {
			return null;
		}
	}
	
	protected ICTac getTacByIndex(int index) {
		String line = getLineByIndex(index);
		if (line != null) {
			return new ICTac(line);
		} else {
			return null;
		}
	}
}
